package com.gopay.bis.service.bank.impl.ebank;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.bis.common.util.constants.BisPayConstants;
import com.gopay.bis.manager.bank.BankOrderManager;
import com.gopay.bis.manager.bank.ebank.IpayManager;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.IPayOrderStatus;
import com.gopay.common.constants.bank.IpayConstants;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BankOrder;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.ipay.ebank.IpayMessage;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.bank.BankInteractRemoteService;

/**
 * 民生i支付业务实现
 * 
 * @IpayBankServiceImpl.java
 * @author lilili
 * @2016年7月8日 下午1:47:25 www.gopay.com.cn Inc.All rights reserved.
 */
public class IpayBankServiceImpl implements BankInteractRemoteService {

	@Resource(name = "iPayManager")
	IpayManager iPayManager;

	@Resource(name = "bankOrderManager")
	private BankOrderManager bankOrderManager;

	@Override
	public Result pay(BaseMessage base) {
		Result result = new Result(false);
		IpayMessage message = new IpayMessage();
		BeanUtils.copyProperties(base, message);
		try {
			message = (IpayMessage) iPayManager.sign(message);
			result.setDefaultModel(message);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
		return result;
	}

    @Override
    public Result refund(BaseMessage base) {
        Result result = new Result(false);        
        try {
            IpayMessage message = new IpayMessage();
            BeanUtils.copyProperties(base, message);
            message = (IpayMessage) iPayManager.refund(message);
            
            if (IpayConstants.BANK_IPAY_DEAL_ERROR.equals(message.getRespType())) {
                // 接收失败               
                result.setModel("falg", false);
            } else {
                // 接收成功
                result.setModel("falg", true);
            }
            result.setModel("retMsg", message.getRespMsg());
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
        }
        return result;
    }


	@Override
	public Result bankBack(BaseMessage base) {
		Result result = new Result(false);
		IpayMessage message = new IpayMessage();
		BeanUtils.copyProperties(base, message);
		try {
			boolean isVerify = (Boolean) iPayManager.verify(message);
			String amount = message.getMoneyOrder();
			BankOrder bankOrder = null;
			bankOrder = bankOrderManager.getBankOrderById(message.getNoOrder());
			message.setOrderId(bankOrder.getOrderId());
			result.setModel("res", message);
			result.setDefaultModel(isVerify);
			result.setSuccess(true);
			if (result != null && result.isSuccess() && (Boolean) result.getDefaultModel()) {
				Map<String, String> param = new HashMap<String, String>();
				if (message.getRespType() != null && message.getRespType().equals(IpayConstants.BANK_IPAY_DEAL_SUCCESS)
						&& message.getRespCode() != null
						&& message.getRespCode().equals(IpayConstants.TRAN_IPAY_DEAL_SUCCESS)) {
					// 如果该订单成功通知后台地址入账
					param.put("orderId", message.getOrderId());
					param.put("amt", amount);
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "");
					param.put("signData", message.getSignMessage());
					param.put("isFront", base.isFront() + "");
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					// 通知后台地址该订单失败
					param.put("orderId", message.getOrderId());
					param.put("amt", amount);
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "");
					param.put("signData", message.getSignMessage());
					param.put("isFront", base.isFront() + "");
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;

	}

    @Override
    public Result refundBack(BaseMessage base) {
        Result result = new Result(false);
        IpayMessage message = new IpayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            boolean isVerify = (Boolean) iPayManager.verify(message);
            result.setModel("res", message);
            String amount = message.getMoneyOrder();
            result.setDefaultModel(isVerify);
            if (result != null && isVerify) {
                Map<String, String> param = new HashMap<String, String>();
                if (IpayConstants.BANK_IPAY_DEAL_SUCCESS.equals(message.getRespType())
                        && IpayConstants.TRAN_IPAY_DEAL_SUCCESS.equals(message.getRespCode())) {
                    // 订单成功
                    param.put("orderId", message.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "00");
                    param.put("retCode", "00");
                    param.put("retMsg", "");
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront() + "");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(true);
                } else {
                    // 通知后台地址该订单失败
                    param.put("orderId", message.getOrderId());
                    param.put("amt", amount);
                    param.put("cardType", "Unknown");
                    param.put("notifyNum", "1");
                    param.put("payStatus", "01");
                    if (IpayConstants.TRAN_IPAY_DEAL_TIMEOUT.equals(message.getRespCode())
                            || IpayConstants.TRAN_IPAY_DEALING.equals(message.getRespCode())) {
                        // 处理中
                        param.put("retCode", message.getRespCode());
                    } else {
                        // 失败
                        param.put("retCode", "01");
                    }

                    if (StringUtils.isBlank(message.getRespMsg())) {
                        // 获取失败信息
                        message.setRespMsg(IPayOrderStatus.getName(message.getRespCode()));
                    }
                    param.put("retMsg", message.getRespMsg());
                    param.put("signData", message.getSignMessage());
                    param.put("isFront", base.isFront() + "");
                    result.setModel("isNotifyCashier", param);
                    result.setOrderStatus(false);
                }
            }
            result.setSuccess(true);
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6088);
        }
        return result;
    }

	@Override
	public Result queryBack(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Result query(BaseMessage base) {
        Result result = new Result(false);
        IpayMessage message = new IpayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            IpayMessage res = (IpayMessage) iPayManager.query(message);
            result.setDefaultModel(res);
            result.setSuccess(true);
            if (BisPayCheckUtils.checkExternalOrderID(base.getOrderId())) {
                Map<String, String> param = new HashMap<String, String>();
                param.put("orderId", base.getOrderId());
                if (res == null) {
                    // 查询订单为空
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "银行返回对账结果为空");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }

                param.put("amount", res.getMoneyOrder());
                if (message.isFlag()){
                    // 成功处理
                    if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_SUCCESS, message.getOriRespCode())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
                        param.put("returnMessage", "交易成功");
                    }
                    // 失败处理
                    else if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_FAIL, message.getOriRespCode())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
                        param.put("returnMessage", message.getOriRespMsg());
                    }else {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        param.put("returnMessage", "银行返回交易未成功");
                    }
                } else {
                    // 查询返回验签失败
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "验签失败");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                result.setModel("queryResult", param);
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
        }
        return result;
    }

	@Override
	public Result dayend(BaseMessage base) {
		Result result = new Result(false);
		IpayMessage message = new IpayMessage();
		BeanUtils.copyProperties(base, message);
		try {
			message = (IpayMessage) iPayManager.dayend(message);
//			Map<String, String> param = new HashMap<String, String>();
//			if (message.isFlag()){
//                // 成功处理
//                if (StringUtils.equals(IpayConstants.BANK_IPAY_DEAL_SUCCESS, message.getRespType())
//                		&&StringUtils.equals(IpayConstants.TRAN_IPAY_DEAL_SUCCESS, message.getRespCode())) {
//                    param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
//                    param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
//                    param.put("content", message.getContent());
//                    param.put("returnMessage", "处理对账文件成功");
//                } else {
//                    param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
//                    param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
//                    param.put("returnMessage", "处理对账文件失败");
//                }
//            } else {
//                // 查询返回验签失败
//                param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
//                param.put("returnMessage", "验签失败");
//                param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
//                result.setModel("queryResult", param);
//                return result;
//            } 
			if (message.isFlag()){//验签成功
                // 成功处理
                if (StringUtils.equals(IpayConstants.BANK_IPAY_DEAL_SUCCESS, message.getRespType())
                		&&StringUtils.equals(IpayConstants.TRAN_IPAY_DEAL_SUCCESS, message.getRespCode())) {
                	result.setDefaultModel(message.getContent());
                }
			}
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6029);
		}
		return result;
	}

    @Override
    public Result refundQuery(BaseMessage base) {
        Result result = new Result(false);
        IpayMessage message = new IpayMessage();
        BeanUtils.copyProperties(base, message);
        try {
            IpayMessage res = (IpayMessage) iPayManager.query(message);
            result.setDefaultModel(res);
            result.setSuccess(true);
            if (BisPayCheckUtils.checkExternalOrderID(base.getOrderId())) {
                Map<String, String> param = new HashMap<String, String>();
                param.put("orderId", base.getOrderId());
                if (res == null) {
                    // 查询订单为空
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "银行返回对账结果为空");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }

                param.put("amount", res.getMoneyOrder());
                if (message.isFlag()){
                    // 成功处理
                    if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_SUCCESS, message.getOriRespCode())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_SUCCESS);
                        param.put("returnMessage", "交易成功");
                    }
                    // 失败处理
                    else if (StringUtils.equals(IpayConstants.QUERY_IPAY_DEAL_FAIL, message.getOriRespCode())) {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_FAIL);
                        param.put("returnMessage", message.getOriRespMsg());
                    } else {
                        param.put("returnCode", BisPayConstants.QUERYSTATE_SUCCESS);
                        param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                        param.put("returnMessage", "银行返回交易失败");
                    }
                } else {
                    // 查询返回验签失败
                    param.put("returnCode", BisPayConstants.QUERYSTATE_FAIL);
                    param.put("returnMessage", "验签失败");
                    param.put("tradeState", BisPayConstants.TRADESTATE_OTHER);
                    result.setModel("queryResult", param);
                    return result;
                }
                result.setModel("queryResult", param);
            }
        } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(e.getErrCode());
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
        }
        return result;
    }

	@Override
	public Result sendBankRefund(BaseMessage base) {
		// TODO Auto-generated method stub
		return null;
	}

}
